import { getTargetRate } from './utils'
import dataTools from '../../../utils/dateTools'
import api from '../../../api/index'
import dayjs from '../../../plugin/dayjs/index';
import { locale } from '../../../plugin/dayjs/dayjs';


Page({
    pageName: '运动推荐/首页',
    data: {
        calanderDate: [],
        static: {
            header: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/intelligent-recommend/sport/header.png',
            playIcon:
                'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/intelligent-recommend/sport/play-icon.png'
        },

        activeDaySport: null,
        targetRate: '',
        resData: null
    },

    onLoad: function (options) {
        // this.fromHome = options.fromHome // 记录页面来源
        this.getTicket()
        
    },  
    async getTicket() {
        try {
            // await app.isLogin({ctx: this})
            const list = await api.post('/api/hxhealth/user/laikangticket')
            console.log(list);
            this.dataInit(list[0].url)
        console.log('haha----------------');
            return list
        } catch (e) {
            return null
        }
    },
    async dataInit (name) {
				wx.showLoading({
					title: '加载中...'
				})
        const data = await this.getData(name)
        console.log('getData', data)
        const { begindate, enddate } = data
        let calanderDate = this.createCalanderDate(begindate, enddate)
        console.log(calanderDate, '日历')
        let num = 1;
for (let i = 0; i < calanderDate.length; i++) {
  if (calanderDate[i].num !== "6" && calanderDate[i].num !== "7") {
    calanderDate[i].num = String(num);
    num++;
  }
}
console.log(calanderDate);
        const activeDaySport = this.getActiveSport(data, calanderDate, 0)

        console.log(activeDaySport)
        const targetRate = getTargetRate(activeDaySport)
        this.setData({
            calanderDate,
            activeDaySport,
            targetRate,
            resData: data
        })
				if(calanderDate.length > 0) {
          calanderDate.forEach((item, index) => {
            if (item.day === dayjs().format('DD')) {
              const obj = {
                index,
                item
              }
							// 进来默认选中当天
							setTimeout(() => {
								this.selectComponent('#minicalendar').changeDate({
									currentTarget: {
										dataset: obj
									}
								})
							}, 200)
              return
            }
          })
        }
        wx.hideLoading()
    },
    createCalanderDate (begin, end) {
        let calanderDateStr = dataTools.getAllDate(begin, end)
        console.log(calanderDateStr)
        let calanderDate = calanderDateStr.map(item => {
            return {
                day: item.split('-')[2],
                week: dataTools.getWeek(item),
                num: dataTools.getWeekNumber(item)
            }
        })
        return calanderDate
    },
    getActiveSport (data, calanderDate, index = 0) {
        console.log(data, '当天选中的运动')
        console.log(calanderDate, '日历')
        const { num: numDay } = calanderDate[index]
        // console.log(JSON.parse(data.data).prescriptions)
        // console.log(JSON.parse(data.data))
        const totalSport = JSON.parse(data.data).prescriptions
        console.log(totalSport, '总运动')
        const activeDaySport =
            totalSport.find(item => item.date === `d${numDay}`) || {}
        return activeDaySport.prescription || null
    },
    handlePlay (e) {
        const item = e.currentTarget.dataset.item
        const { url: src } = item
        const url = `/sportsRecommendations/pages/play/index?src=${src}`
        wx.navigateTo({
            url
        })
    },
    onDateChange (v) {
        const { num, idx } = v.detail
        this.setData({
            num
        })
        if (num == '6' || num == '7') {
            return
        }
        const activeDaySport = this.getActiveSport(
            this.data.resData,
            this.data.calanderDate,
            idx
        )
        this.setData({
            activeDaySport
        })
    },
    getData (name) {
        return new Promise((resolve, reject) => {
            const url = `${name}/api/health/recommend/exercise?`
            api.adminGet(url)
                .then(res => {
                    console.log('请求的结果res', res)
                    resolve(res[0])
                })
                .catch(e => {
                    console.log('进入异常', e)
                    wx.showToast({
                        title: e.faultstring,
                        icon: 'none'
                    })
                    wx.hideLoading()
                    reject(e)
                })
        })
    }
})
